package com.dingwen.lir.controller;

import com.dingwen.lir.entity.User;
import com.dingwen.lir.filter.RequestWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Arrays;

/**
 * @author dingwen
 * 2021.04.26 18:03
 */
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    private final HttpSession httpSession;

    @Autowired
    UserController(HttpSession httpSession) {
        this.httpSession = httpSession;
    }

    /*
     * 登录
     * Spring boot后台接收前端传过来的form-date类型的参数
     * @param user
     * @return User
     */
    @PostMapping("/login")
    public void login(String account, String password, HttpServletResponse response) {
        User user = new User();
        user.setAccount(account);
        user.setPassword(password);
        httpSession.setAttribute("user", user);
        try {

            if (StringUtils.hasText(account) && StringUtils.hasText(password)) {
                response.sendRedirect("/page/user");
            } else {
                response.sendRedirect("/page/login");
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /*
     *
     * 退出登录
     */
    @GetMapping("/logout")
    public void logout() {
        httpSession.invalidate();
    }


    /*
     *使用自定义 RequestWrapper 修改request内容
     * 测试
     */
    @GetMapping("/test")
    public void test(RequestWrapper requestWrapper) {
        log.info("test:{}", Arrays.toString(requestWrapper.getParameterValues("name")));
    }

}
